package com.jml; 
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * 手写jwt
 */
public class JWTDemo05 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        // 手写一个jwt的案例
        /**
         * 头部
         * payload
         * 验证签名
         */
        // header
        JSONObject header = new JSONObject();
        header.put("Alg", "HS256");
        // payLoad
        JSONObject payLoad = new JSONObject();
        payLoad.put("userName", "jml644");
        payLoad.put("userAge", "21");
        payLoad.put("userId", "18888");
//        payLoad.put("rd", System.currentTimeMillis());
        // base64 对实现数据编码
        String jwtHeader = Base64.getEncoder().encodeToString(header.toJSONString().getBytes());
        String jwtPayLoad = Base64.getEncoder().encodeToString(payLoad.toJSONString().getBytes());
        //盐值
        String signingKey = "jmlKey";
        // 签名 后面在加盐 存放服务器端
        String sign = DigestUtils.md5Hex(payLoad.toJSONString() + signingKey);
        String jwt = jwtHeader + "." + jwtPayLoad + "." + sign;
        System.out.println(jwt);
        // 解密
        String payLoadStr = new String(Base64.getDecoder().decode(jwt.split("\\.")[1].getBytes()), "UTF-8");
        String jwtSign = jwt.split("\\.")[2];
        //验证签名
        System.out.println(DigestUtils.md5Hex(payLoadStr + signingKey).equals(jwtSign));
    }
}
